﻿using Lanbt.Core.Entity.Dto.lanbt_system_config;
using Lanbt.Core.Service.SqlService.IService;
using Lanbt.Core.Utility;
using Lanbt.Core.Utility.ExceptionExtent;
using Lanbt.Core.Utility.Extent;
using MailKit.Net.Imap;
using MailKit.Net.Pop3;
using MailKit.Net.Smtp;
using Microsoft.Extensions.DependencyInjection;
using MimeKit;
using Org.BouncyCastle.Utilities.Encoders;

namespace Lanbt.Core.Service.Helper
{
    /// <summary>
    /// 邮箱帮助类
    /// </summary>
    public class EmailHelper
    {
        private readonly static IConfigService _systemConfigService;

        static EmailHelper()
        {
            _systemConfigService = GlobalContext.ServiceProvider.GetService<IConfigService>();
        }

        /// <summary>
        /// 初始化邮箱客户端
        /// </summary>
        /// <param name="mimeMessage"></param>
        /// <returns></returns>
        public static async Task InitEmailClient(MimeMessage mimeMessage)
        {
            //获取邮箱配置信息
            var result = await _systemConfigService.GetSystemConfig(Entity.Enums.SystemConfigKey.SystemEmail);
            var mailConfig = result.Result.JsonToObject<MailConfig>();
            if (mailConfig.is_mail_enable)
            {
                mimeMessage.From.Add(new MailboxAddress(mailConfig.send_mail_name, mailConfig.send_mailbox));
                using (SmtpClient client = new SmtpClient())
                {
                    //Smtp服务器
                    client.Connect(mailConfig.mail_server_addr, mailConfig.mail_server_port, mailConfig.is_mail_ssl_enable);
                    if (client.IsConnected)
                    {
                        //登录  yzy授权码：LYRKQYPMNQPIWLNS
                        client.Authenticate(mailConfig.send_mailbox, mailConfig.mail_code);
                        //发送
                        client.Send(mimeMessage);
                    }
                    //断开
                    client.Disconnect(true);
                }
            }
        }

        /// <summary>
        /// 给白名单邮箱发送
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        public static async Task SendToSystem(string title,string content)
        {
            //获取邮箱配置信息
            var result = await _systemConfigService.GetSystemConfig(Entity.Enums.SystemConfigKey.SystemEmail);
            var mailConfig = result.Result.JsonToObject<MailConfig>();
            if (mailConfig.receiv_mail.IsNotNullOrEmpty())
            {
                var mails = mailConfig.receiv_mail.LanbtSplit(',');
                var mimeMessage = new MimeMessage();
                foreach (var item in mails)
                {
                    mimeMessage.To.Add(new MailboxAddress(item.Split('@')[0], item));
                }
                if(mimeMessage.To.Count == 0)
                {
                    return;
                }
                mimeMessage.Subject = title;
                var alternative = new Multipart("alternative");
                alternative.Add(new TextPart("plain") { Text = content });

                mimeMessage.Body = alternative;

                await InitEmailClient(mimeMessage);
            }
        }

        /// <summary>
        /// 单个邮箱发送信息
        /// </summary>
        /// <param name="inEmail"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        public static async Task Send(string inEmail,string title,string content)
        {
            var mimeMessage = new MimeMessage();
            mimeMessage.To.Add(new MailboxAddress(inEmail.Split('@')[0], inEmail));
            mimeMessage.Subject = title;
            var alternative = new Multipart("alternative");
            alternative.Add(new TextPart("plain") { Text = content });

            mimeMessage.Body = alternative;

            await InitEmailClient(mimeMessage);
        }

        /// <summary>
        /// 多个邮箱发送信息
        /// </summary>
        /// <param name="inEmail"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        public static async Task Send(List<string> inEmail, string title, string content)
        {
            var mimeMessage = new MimeMessage();
            foreach (var item in inEmail)
            {
                mimeMessage.To.Add(new MailboxAddress(item.Split('@')[0], item));
            }
            mimeMessage.Subject = title;
            var alternative = new Multipart("alternative");
            alternative.Add(new TextPart("plain") { Text = content });

            mimeMessage.Body = alternative;

            await InitEmailClient(mimeMessage);
        }

        public static Task TestMailClient(MailConfig mailConfig)
        {
            using (SmtpClient client = new SmtpClient())
            {
                try
                {
                    client.Connect(mailConfig.mail_server_addr, mailConfig.mail_server_port, mailConfig.is_mail_ssl_enable);
                    client.Authenticate(mailConfig.send_mailbox, mailConfig.mail_code);
                }
                catch(Exception ex)
                {
                    throw new LanbtException(ExceptionModel.EXCEPTION, ex.Message);
                }
            }
            return Task.CompletedTask;
        }
    }
}
